package com.wdh.networklibrary.net;

import android.text.TextUtils;

import com.erongdu.wireless.tools.log.Logger;
import com.wdh.networklibrary.mvp.view.BaseView;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;

import retrofit2.HttpException;

public class NetError {

    public static void onError(Throwable t, BaseView view) {
        if (null != view) {
            Logger.i("toast", "onError:" + t.getMessage());
            String msg;
            if (t instanceof HttpException) {
                /*网络异常*/
                msg = "网络异常，请确保网络可用!";
            } else if (t instanceof ConnectException || t instanceof SocketTimeoutException) {
                msg = "请求超时，请稍后重试!";
            } else if (t instanceof JSONException || t instanceof ParseException) {
                /*解析异常*/
                msg = "数据解析异常，请稍后重试!";
            } else if (t instanceof UnknownHostException) {
                /*无法解析该域名异常*/
                msg = "无法解析该域名，请稍后重试!";
            } else {
                msg = "请求失败，请稍后重试!";
            }
            if (TextUtils.isEmpty(msg)) {
                view.onFailure(t.getMessage());
            } else {
                view.onFailure(msg);
            }
        }
    }


    public static String onError(Throwable t) {

        String msg;
        if (t instanceof HttpException) {
            /*网络异常*/
            msg = "网络异常，请确保网络可用!";
        } else if (t instanceof ConnectException || t instanceof SocketTimeoutException) {
            msg = "请求超时，请稍后重试!";
        } else if (t instanceof JSONException || t instanceof ParseException) {
            /*解析异常*/
            msg = "数据解析异常，请稍后重试!";
        } else if (t instanceof UnknownHostException) {
            /*无法解析该域名异常*/
            msg = "无法解析该域名，请稍后重试!";
        } else {
            msg = "请求失败，请稍后重试!";
        }
        if (TextUtils.isEmpty(msg)) {
            return t.getMessage();
        } else {
            return msg;
        }
    }
}
